namespace Digitalmes.Common.Utils;

/// <summary>
/// HTTP 帮助类
/// </summary>
public static class HttpUtils
{
    /// <summary>
    /// 获得访问的IP地址
    /// </summary>
    /// <returns>字符串数组</returns>
    public static string GetIp()
    {
        HttpContextAccessor context = new();
        var headers = context.HttpContext?.Request.Headers;
        if (headers != null)
        {
            if (headers.TryGetValue("X-Real-IP", out var ip))
            {
                return ip!;
            }

            if (headers.TryGetValue("X-Forwarded-For", out var forwarded))
            {
                return forwarded!;
            }
        }

        return context.HttpContext?.Connection.RemoteIpAddress?.ToString() ?? "";
    }

    /// <summary>
    /// 获得访问的浏览器信息
    /// </summary>
    /// <returns>字符串数组</returns>
    public static string GetBrowser()
    {
        HttpContextAccessor context = new();
        var browserAgent = context.HttpContext?.Request.Headers["User-Agent"].ToString();
        if (string.IsNullOrEmpty(browserAgent))
        {
            return "";
        }

        if (browserAgent.Contains("Chrome")) return "Chrome";
        if (browserAgent.Contains("Safari")) return "Safari";
        if (browserAgent.Contains("Firefox")) return "Firefox";
        if (browserAgent.Contains("Edge")) return "Microsoft Edge";
        if (browserAgent.Contains("Opera")) return "Opera";
        if (browserAgent.Contains("MSIE")) return "IE";

        return "";
    }
}
